<?php

class DateUtils {

	const YEAR = 0;
	const MONTH = 1;
	const DAY = 2;
	const HOUR = 3;
	const MINUTE = 4;
	const SECOND = 5;
	const MILLISECOND = 6;

	public static function today() {
		return self::truncate(new Date(), self::DAY);
	}

	public static function truncate($date, $field) {
		$v = new Date($date->getTime());
		switch($field) {
			case self::YEAR:
				$v->setMonth(0);
			case self::MONTH:
				$v->setDate(1);
			case self::DAY:
				$v->setHours(0);
			case self::HOUR:
				$v->setMinutes(0);
			case self::MINUTE:
				$v->setSeconds(0);
			case self::SECOND:
				$v->setMilliseconds(0);
		}

		return $v;
	}

	public static function add($date, $field, $amount) {
		$v = new Date($date->getTime());
		switch($field) {
			case self::YEAR:
				$v->setYear($v->getYear()+$amount);
				break;
			case self::MONTH:
				$v->setMonth($v->getMonth()+$amount);
				break;
			case self::DAY:
				$v->setDay($v->getDay()+$amount);
				break;
			case self::HOUR:
				$v->setHours($v->getHours()+$amount);
				break;
			case self::MINUTE:
				$v->setMinutes($v->getMinutes()+$amount);
				break;
			case self::SECOND:
				$v->setSeconds($v->getSeconds()+$amount);
				break;
			case self::MILLISECOND:
				$v->setMilliseconds($v->getMilliseconds()+$amount);
				break;
		}

		return $v;
	}

	public static function isSameDay($d1, $d2) {
		$_d1 = self::truncate(d1, self::DAY);
		$_d2 = self::truncate(d2, self::DAY);

		return $_d1->getTime() == $_d2->getTime();
	}

	public static function isSameMoment($d1, $d2, $field) {
		$_d1 = self::truncate($d1, $field);
		$_d2 = self::truncate($d2, $field);

		return $_d1->getTime() == $_d2->getTime();
	}

	public static function isSameInstant($d1, $d2) {
		return $d1->getTime() == $d2->getTime();
	}

	public static function daysDiff ($d1, $d2) {
		$d = self::truncate($d1, self::DAY)->getTime() - self::truncate($d2, self::DAY)->getTime();
		return (int)($d / (24 * 60 * 60));
	}

	public static function diff ($d1, $d2, $field) {
		$d = self::truncate($d1, $field)->getTime() - self::truncate($d2, $field)->getTime();
		$f = 1;
			
		switch($field) {
			case DateUtils.YEAR:
				$d = $d1->getYear() - $d2->getYear();
				break;

			case DateUtils.MONTH:
				$d = ($d1->getYear() - $d2->getYear())*12 + $d1->getMonth() - $d2->getMonth();
				break;

			case DateUtils.DAY:
				$f = $f*24;
			case DateUtils.HOUR:
				$f = $f*60;
			case DateUtils.MINUTE:
				$f = $f*60;
			case DateUtils.SECOND:
				$f = $f*1000;
		}

		return $d / $f;
	}

	/*parse = function (fmt, s) {
		return $.datepicker.parseDate(fmt, s);
		};*/

	public static function format($fmt, $d) {
		return date($fmt, $d->getTime());
	}
	
	public static function parse($fmt, $d) {
		$ts = CDateTimeParser::parse($d, $fmt);
		return new Date($ts);
	}

}